//
//  ZTabBar.m
//  Zlottery
//
//  Created by HuaYingJiTuan on 16/1/8.
//  Copyright © 2016年 张庆庆. All rights reserved.
//

#import "ZTabBar.h"

@interface ZTabBar ()
@property (nonatomic, strong) UIButton *preButton;
@end

@implementation ZTabBar
- (void)addTabBarItem:(NSString *)imgName selectedImgName:(NSString *)selectedImgName{
    ZTabBarButton *btn = [ZTabBarButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:btn];
    
    [btn setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:selectedImgName] forState:UIControlStateSelected];
    
    [btn sizeToFit];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
    
    //不允许高亮的时候修改图片
    btn.adjustsImageWhenHighlighted = NO;
    if (self.subviews.count == 1) {
        [self btnClick:btn];
    }
}
- (void)btnClick:(UIButton *)sender{
    self.preButton.selected = NO;
    sender.selected = YES;
    
    if ([self.delegate respondsToSelector:@selector(tabBarDidClickedBtn:fromIndex:toIndex:)]) {
        [self.delegate tabBarDidClickedBtn:self fromIndex:self.preButton.tag toIndex:sender.tag];
    }
    self.preButton = sender;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    for (int i = 0; i < self.subviews.count; i++) {
        UIButton *btn = self.subviews[i];
        btn.layer.anchorPoint = CGPointMake(0, 0);
        btn.center = CGPointMake(i*btn.frame.size.width, 0);
        btn.tag = i;
    }
}
@end
